<script setup>
import {ref} from "vue";
import { useRouter, useRoute } from "vue-router";
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import {http} from "@/api";
import useTable from "@/utils/useTable";
import { getStatus } from "@/utils/common";

const apiKey = 'ProductOrder'
const router = useRouter()
const route = useRoute()
const id = route.params.id
const formData = ref({
  member: {},
  address: {}
})
const rules = ref({
  name: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
})
const getOrderType = (type) => {
  /**
   * 0 自提
   * 1 同城配送
   * 2 快递
   */
  switch (type) {
    case 0:
      return '自提'
    case 1:
      return '同城配送'
    case 2:
      return '快递'
  }
}

const formRef =  ref(null)
const getOrderDetail = () => {
  http[apiKey].read(id).then(res => {
    formData.value = {
      ...res.data,
      member: res.data.member || {},
      address: res.data.address || {}
    }
    address.value = res.data.address || {}
    sendFormModel.value.address_id = res.data.address_id
    sendFormModel.value.express_code = res.data.express_code
    sendFormModel.value.express_no = res.data.express_no
    sendFormModel.value.express_info = res.data.express_info ? (JSON.parse(res.data.express_info) || []) : []
    if (res.data.member_id) {
      http.MemberAddress.list({
        member_id: res.data.member_id
      }).then(res => {
        addressList.value = res.data
      })
    }
  })
}
if (id) {
  // 获取详情
  getOrderDetail()
}
const addressList = ref([])

const {
  pageNo,
  pageSize,
  total,
  changePage,
  changeSize,
  dataSource,
  search,
  reset,
  openDelete
} = useTable({
  requestFn: http.ProductOrderDetail,
  routerPre: 'ProductOrderDetail',
  params: {
    name: '',
    order_id: id
  }
})
const saveProduct = (row) => {
  ElMessageBox.confirm(
      '是否确认更改订单信息？',
      '提示',
      {
        confirmButtonText: '确认更改',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        http.ProductOrderDetail.update({
          id: row.id,
          count: row.count
        }).then(res => {
          ElMessage({
            type: 'success',
            message: '更改成功',
          })
          search()
getOrderDetail()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '更改取消',
        })
      })
}
const expressList = ref([
  {
    id: 1,
    name: '顺丰快递'
  },
  {
    id: 2,
    name: '圆通快递'
  },
  {
    id: 3,
    name: '中通快递'
  },
  {
    id: 4,
    name: '申通快递'
  },
  {
    id: 5,
    name: '韵达快递'
  }
])
// 发货
const dialogVisible = ref(false)
const sendFormModel = ref({
  express_code: '',
  express_no: '',
  address_id: '',
  express_info: []
})
const sendRules = ref({
  express_code: [
    { required: true, message: '请选择物流快递', trigger: 'change' },
  ],
  express_no: [
    { required: true, message: '请输入物流单号', trigger: 'blur' },
  ],
  address_id: [
    { required: true, message: '请选择地址', trigger: 'change' },
  ],
})
const address = ref({})
const sendFormRef = ref(null)
const send = () => {
  dialogVisible.value = true
}
const sendSave = () => {
  sendFormRef.value.validate((valid) => {
    if (valid) {
      const loadingInstance = ElLoading.service()
      http.ProductOrder.update({
        id: id,
        status: 3,
        express_code: sendFormModel.value.express_code,
        express_info: JSON.stringify(sendFormModel.value.express_info),
        address_id: sendFormModel.value.address_id,
        express_no: sendFormModel.value.express_no
      }).then(res => {
        ElMessage.success('发货成功')
        dialogVisible.value = false
        search()
getOrderDetail()
      }).finally(() => {
        loadingInstance.close()
      })
    } else {
      console.log('error submit!!')
      return false
    }
  })

}

const updateExpressInfo = () => {
  dialogVisible.value = true
}
const addExpressInfo = () => {
  sendFormModel.value.express_info.push({
    title: '',
    date: '',
    content: ''
  })
}
const send2 = () => {
  ElMessageBox.confirm(
      '是否确认自提发货？',
      '提示',
      {
        confirmButtonText: '确认自提发货',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        http.ProductOrder.update({
          id: id,
          status: 4
        }).then(res => {
          ElMessage({
            type: 'success',
            message: '自提发货成功',
          })
          getOrderDetail()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '自提发货取消',
        })
      })
}
const send3 = () => {
  ElMessageBox.confirm(
      '是否确认同城配送到达？',
      '提示',
      {
        confirmButtonText: '确认到达',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        http.ProductOrder.update({
          id: id,
          status: 4
        }).then(res => {
          ElMessage({
            type: 'success',
            message: '同城配送到达成功',
          })
          getOrderDetail()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '自提发货取消',
        })
      })
}
const sendConfirm = () => {
  ElMessageBox.confirm(
      '是否确认到达？',
      '提示',
      {
        confirmButtonText: '确认到达',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        http.ProductOrder.update({
          id: id,
          status: 4
        }).then(res => {
          ElMessage({
            type: 'success',
            message: '确认成功',
          })
          search()
          getOrderDetail()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '确认取消',
        })
      })
}
const agreeBack = () => {
  ElMessageBox.confirm(
      '是否确认同意退货？',
      '提示',
      {
        confirmButtonText: '确认同意退货',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        http.ProductOrder.update({
          id: id,
          order_status: 2,
        }).then(res => {
          ElMessage({
            type: 'success',
            message: '同意退货成功',
          })
          search()
          getOrderDetail()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '同意退货取消',
        })
      })
}
const rejectBack = () => {
  ElMessageBox.confirm(
      '是否拒绝同意退货？',
      '提示',
      {
        confirmButtonText: '确认拒绝退货',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        http.ProductOrder.update({
          id: id,
          order_status: 3,
        }).then(res => {
          ElMessage({
            type: 'success',
            message: '拒绝退货成功',
          })
          search()
getOrderDetail()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '拒绝退货成功取消',
        })
      })
}
</script>

<template>
<!--  发货-->
  <el-dialog
      v-model="dialogVisible"
      title="发货"
      width="800px"
  >
    <el-form label-position="top" label-width="80px" ref="sendFormRef" :model="sendFormModel" :rules="sendRules">
      <el-form-item label="地址" prop="address_id">
        <el-select v-model="sendFormModel.address_id">
          <el-option
              v-for="item in addressList"
              :key="item.id"
              :label="item.address + '【' +item.username + '-' + item.phone  + '】'"
              :value="item.id"
          >
            <span style="float: left">{{ item.address + '【' +item.username + '-' + item.phone  + '】' }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物流快递" prop="express_code">
        <el-select v-model="sendFormModel.express_code">
          <el-option
              v-for="item in expressList"
              :key="item.name"
              :label="item.name"
              :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物流快递" prop="express_no">
        <el-input placeholder="请输入标题" v-model="sendFormModel.express_no"></el-input>
      </el-form-item>
      <el-form-item label="物流信息">
        <el-row style="width: 100%;margin-bottom: 20px" :gutter="20" v-for="item in sendFormModel.express_info">
          <el-col :span="6">
            <el-input placeholder="请输入标题" v-model="item.title"></el-input>
          </el-col>
          <el-col :span="8">
            <el-date-picker
                v-model="item.date"
                type="datetime"
                placeholder="请选择日期时间"
            />
          </el-col>
          <el-col :span="10">
            <el-input placeholder="请输入物流内容" v-model="item.content"></el-input>
          </el-col>
        </el-row>
        <el-row style="width: 100%">
          <el-button @click="addExpressInfo" type="primary" style="width: 100%">添加</el-button>
        </el-row>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sendSave">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <PageMain title="订单详情">
    <div class="form-content f-c">
      <el-card shadow="never" class="f-s">
        <template #header>
          <div class="card-header">
            <span>订单信息</span>
          </div>
        </template>
        <el-descriptions
            :column="2"
            border
        >
          <el-descriptions-item>
            <template #label>
              订单号：
            </template>
            {{ formData.order_no }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              订单状态：
            </template>
            {{ getStatus(formData) }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              用户姓名：
            </template>
            {{ formData.member.nickname }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              用户电话：
            </template>
            {{ formData.member.phone }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              优惠券：
            </template>
            {{ formData?.coupon?.name }}
          </el-descriptions-item>
        </el-descriptions>

      </el-card>
      <div style="height: 20px"></div>

      <el-card shadow="never" class="f-s" v-if="formData.address_id">
        <template #header>
          <div class="card-header">
            <span>地址信息</span>
          </div>
        </template>
        <el-descriptions   :column="2"
                           border>
          <el-descriptions-item label="姓名">
            {{ address.username }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ address.phone }}
          </el-descriptions-item>
          <el-descriptions-item label="地址">
            {{ address.address }}
          </el-descriptions-item>
          <el-descriptions-item label="门牌号">
            {{ address.code }}
          </el-descriptions-item>
          <el-descriptions-item label="出生日期">
            {{ address.birthday }}
          </el-descriptions-item>
          <el-descriptions-item label="八字">
            {{ address.bazi }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <div style="height: 20px"></div>
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>商品明细</span>
          </div>
        </template>
        <el-table :data="dataSource">
          <el-table-column label="商品名称" prop="good.name">
          </el-table-column>
          <el-table-column label="数量" prop="count">
          </el-table-column>
          <el-table-column label="单价" prop="good.price">
          </el-table-column>
          <el-table-column label="商品提示" prop="good.tips">
          </el-table-column>
          <el-table-column label="商品备注" prop="remark">
          </el-table-column>
          <el-table-column label="创建时间" prop="create_time">
          </el-table-column>
        </el-table>
      </el-card>
      <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[10, 50, 100, 200]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="changeSize"
          @current-change="changePage"
      />
    </div>
  </PageMain>
</template>
